package tang.client;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @author Tang
 * @classname ZkClientMain
 * @description [  ]
 * @date 2021/2/23 20:52
 */
public class ZkClientMain {

    private static final Integer port = 9000;
    private static final String host = "127.0.0.1";

    private ClientCnxn clientCnxn;
    private Zookeeper zookeeper;

    public ZkClientMain() {
        connectionZk();
    }

    private void connectionZk() {
        InetSocketAddress address = new InetSocketAddress(host,port);
        // 客户端上下文
        clientCnxn = new ClientCnxn(address,getClientCnxnSocket());
        // 启动线程
        clientCnxn.start();
        // 客户端工具类
        zookeeper = new Zookeeper(clientCnxn);
    }

    public static void main(String[] args) {
        ZkClientMain zkClientMain = new ZkClientMain();
        zkClientMain.run();
    }

    private void run() {
        Scanner scanner = new Scanner(System.in);
        String cmd;
        while (scanner.hasNextLine()) {
            cmd = scanner.nextLine();
            this.processCmd(cmd);
        }
    }

    private void processCmd(String cmd) {

        if (cmd.startsWith("create")) {
            zookeeper.create(cmd);
        }

    }

    private ClientCnxnSocketNIO getClientCnxnSocket() {

        try {
            Class<?> aClass = Class.forName("tang.client.ClientCnxnSocketNIO");
            return (ClientCnxnSocketNIO) aClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}